// Defaults
var koi_mirror = 0;
var koi_method = 0;
var koi_action = 'install';


window.addEvent('domready',function () {
    // Bottom bar
    $('koiline').setStyle('opacity',0.5);
    var koilinefx = new Fx.Style($('koiline'),'opacity',{'wait':false});
    $('koiline').addEvent('mouseenter',function () {koilinefx.start(0.9);});
    $('koiline').addEvent('mouseleave',function () {koilinefx.start(0.5);});
    
    // Menu
    $('koimenu').addEvent('mouseenter',function () {$('koiadvanced').setStyle('display','block');});
    $('koimenu').addEvent('mouseleave',function () {$('koiadvanced').setStyle('display','none');});
    // Menu items
    $('koi_showlog').addEvent('click',koi_showlog);
    $('koi_showmirror').addEvent('click',koi_showmirror);
    $('koi_showmethod').addEvent('click',koi_showmethod);
    $('koi_showaboutproj').addEvent('click',koi_showaboutproj);
    $('koi_showabout').addEvent('click',koi_showabout);
    
    $('koilog').setStyle('opacity',0.8);
});



////////////////////////////////////////////////////
// Callbacks

function koi_startcallback() {
    koi_addlog('Koi Initiated','event');
    
    $('koi_showmirror').setStyle('display','none');
    $('koi_showmethod').setStyle('display','none');
    
    koi_switchboard("start");
}

var koi_alertstage = false
function koi_alertcallback() {
    if (koi_alertstage) {
        koi_addlog('Alert cleared ('+koi_alertstage+')','event');
    } else {
        koi_addlog('Alert cleared (no stage)','event');
    }
    
    var tmp = koi_alertstage;
    koi_alertstage = false;
    
    switch (tmp) {
        case 'overwrite': koi_filestep('install',koi_tmp);
        case 'refresh': location.refresh(); break;
        case 'selectmirror': koi_hidemirror(); break;
        case 'selectmethod': koi_hidemethod(); break;
    }
}

function koi_addlog(text,type) {
    text = text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
    
    switch (type) {
        case 'event': text = "<span>"+text+"</span>"; break;
        case 'warning': text = "<span style=\"background-color:#fff; color:#9b9115;\">"+text+"</span>"; break;
        case 'error': text = "<span style=\"background-color:#fbe1c5;\">"+text+"</span>"; break;
        default: text = text+"\n"; break;
    }
    $('koilogpre').innerHTML = $('koilogpre').innerHTML + text;
}



////////////////////////////////////////////////////
// Menu Items

function koi_showlog() {
    $('koiadvanced').setStyle('display','none');
    $('koilog').setStyle('display','block');
}

function koi_showmirror() {
    koi_alertstage = 'selectmirror';
    $('koiadvanced').setStyle('display','none');
    $('koi_mirror'+koi_mirror).checked = true;
    koi_alert('<div id="koi_hold"><h2>Select Mirror</h2></div>');
    $('koimirror').injectInside('koi_hold');
    $('koimirror').setStyle('display','block');
}
function koi_hidemirror() {
    $('koimirror').getElements('input[type=radio]').each(function(el){
        if(el.getValue()) koi_mirror = el.getValue();
    });
    
    $('koimirror').setStyle('display','none');
    $('koimirror').injectBefore('koiline');
    
    koi_addlog('Mirror changed to '+koi_mirror);
}

function koi_showmethod() {
    koi_alertstage = 'selectmethod';
    $('koiadvanced').setStyle('display','none');
    $('koi_method'+koi_method).checked = true;
    koi_alert('<div id="koi_hold"><h2>Select Method</h2></div>');
    $('koimethod').injectInside('koi_hold');
    $('koimethod').setStyle('display','block');
}
function koi_hidemethod() {
    $('koimethod').getElements('input[type=radio]').each(function(el){
        if(el.getValue()) koi_method = el.getValue();
    });
    $('koimethod').setStyle('display','none');
    $('koimethod').injectBefore('koiline');
    
    koi_addlog('Method changed to '+koi_method);
}

function koi_showaboutproj() {
    koi_alert('<div id="koi_hold"></div>');
    $('koiaboutproj').clone().setStyle('display','block').injectInside('koi_hold');
}
function koi_showabout() {
    koi_alert('<div id="koi_hold"></div>');
    $('koiabout').clone().setStyle('display','block').injectInside('koi_hold');
}






////////////////////////////////////////////////////
// The meat of it

var koi_stagelength=0;
var koi_curstage=0;
function koi_nextstage() {
    koi_curstage++;
    return (100/koi_stagelength)*koi_curstage;
}

var koi_filelist;
var koi_pointer=0;
var koi_tmp=0;
function koi_filestep(type,time) {
    if (!koi_filelist[koi_pointer]) {
        koi_pointer = 0;
        switch (type) {
            case 'download': koi_filestep('scan',time); break;
            case 'scan':
                if (!overwrite) {
                    koi_filestep('install',time);
                } else {
                    koi_alertstage = 'overwrite';
                    koi_tmp = time;
                    koi_alert("<p>The installation will overwrite " + overwrite + " existing files.</p><p>Are you sure you want to continue? Refresh this page to cancel</p>");
                }
                break;
            case 'install': koi_request('cleanup'); break;
        }
        return;
    }
    
    var file = koi_filelist[koi_pointer];
    koi_pointer++;
    
    koi_addlog('Filestep :: '+type+' :: '+koi_pointer,'event');
    koi_addlog('File: '+file.name);
    if (type=='download') koi_addlog('File Hash: '+file.hash);
    
    switch (type) {
        case 'download': koi_change(type,'Downloading file <span id="koi_num">'+koi_pointer+'</span>/'+koi_filelist.length,koi_nextstage(),time); break;
        case 'scan': koi_change(type,'Scanning file <span id="koi_num">'+koi_pointer+'</span>/'+koi_filelist.length,koi_nextstage(),time); break;
        case 'install': koi_change(type,'Installing file <span id="koi_num">'+koi_pointer+'</span>/'+koi_filelist.length,koi_nextstage(),time); break;
    }
    
    koi_request(type,file.name,file.hash);
}

var start=false;
function koi_request(stage,file,hash) {
    if (!file) file = '';
    if (!hash) hash = '';
    start = new Date();
    
    var send = '?'+Object.toQueryString({
        'stage':stage,
        'method':koi_method,
        'mirror':koi_mirror,
        'action':koi_action,
        'file':file,
        'hash':hash
    });
    
    koi_addlog("Send: "+send);
    
    new Ajax(send,{
        method:'get',
        onComplete: function(json){
            koi_addlog("Response: "+json);
            
            try {
                var json = Json.evaluate(json);
            } catch(err) {
                koi_addlog("Response JSON failed to evaluate - "+err,'error');
                koi_error("Response JSON failed to evaluate");
                koi_alert('<h2>Unexpected Error</h2><p>There was an unexpected error when attempting the last action. Please check the connection log (Advanced&nbsp;&gt;&nbsp;View&nbsp;Log) in the menu to the bottom left of the page.</p><p>If you cannot fix the problem yourself then please add a new issue report with Koi (link at bottom right of page) and include the contents of the connection log</p>');
                return false;
            }
            
            // Koi installer is usually too fast for the eye to
            // keep track of, let alone the progress bar effects
            var stop = new Date();
            var time = (stop.getTime() - start.getTime());
            if (time < 1200) {
                koi_addlog("Deferred response...");
                time += 800;
                (function(){koi_switchboard(stage,json,time);}).delay(800);
            } else {
                koi_switchboard(stage,json,time);
            }
        },
        onFailure: function(){
            koi_error('Unknown error during JSON request');
        }
    }).request();
}

var newwrite=0;
var overwrite=0;
function koi_switchboard(stage,response,time) {
    if (!stage) stage = "start";
    
    if ( (response) && (response.error) ) {
        koi_alert("<h2>Error</h2><p>"+response.error+"</p>");
        koi_error("Error in "+stage);
        return;
    }
    
    switch (stage) {
        case "cleanup":
            if (response.fail) koi_alert(response.fail);
            koi_addlog('Shutting down...','event');
            koi_change("cleanup","Cleaning Up",100,time);
            break;
        case "install":
            koi_filestep('install',time);
            break;
        case "scan":
            if (response.overwrite[0]) overwrite = overwrite + response.overwrite.length;
            if (response.newwrite[0]) newwrite = newwrite + response.newwrite.length;
            
            koi_filestep('scan',time);
            break;
        case "download":
            koi_filestep('download',time);
            break;
        case "refresh":
            koi_alertstage = 'refresh';
            koi_alert("<p>This download.php file was out of date and has been updated</p><p>Click Ok to refresh the installer</p>");
            break;
        case "filecheck":
            // Method & mirror auto-select
            if (response.method) koi_method = response.method;
            if (response.mirror) koi_mirror = response.mirror;
            
            // Out of date
            if (response.mincompatable > 1) {
                koi_addlog('Need update','event');
                koi_change(false,"Updating...",100,time);
                koi_request('refresh');
                return;
            }
            
            // No download
            if (!response.mincompatable) {
                koi_addlog('All downloads failed','error');
                koi_downloaderror();
                koi_error("Offline install neccesary");
                return;
            }
            
            // Set globals
            koi_stagelength = (response.files.length * 3) + 1;
            koi_filelist = response.files;
            
            koi_addlog('Stage length = '+koi_stagelength);
            
            // Off we go
            koi_filestep('download',time);
            break;
        case "start":
            koi_change(false,"Querying package servers",0,0);
            koi_request('filecheck');
            break;
    }
}